import "./index.less";
import "@cs/index_footer/index.ts";

declare const $: any;

export default $(function () {
  let flag = true;
  let time = 0;
  if ($("#times").attr("s")) {
    time = $("#times").attr("s") * 60;
  } else {
    time = 20 * 60;
  }
  $("#times").text(`${addzero(Math.floor(time / 60))}:${addzero(time % 60)}`)
  let timer = setInterval(() => {
    time -= 1
    $("#times").text(`${addzero(Math.floor(time / 60))}:${addzero(time % 60)}`)
    if (time == 0) {
      flag = false;
      $(document).find("button[type='submit']").click();
      clearInterval(timer)
    }
  }, 1000)

  function addzero(num) {
    if (num < 10) {
      return '0' + num;
    } else {
      return num
    }
  }
  function toast(title: string) {
    var $textToast = $('#textToast');
    if ($textToast.css('display') != 'none') return;
    if (title) {
      $(".weui-toast__content").text(title);
    }
    $textToast.fadeIn(100);
    setTimeout(function () {
      $textToast.fadeOut(100);
    }, 2000);
  }
  let apply = true;
  $(document).on("click", "button[type='submit']", function (e: any) {
    e = e || window.event
    e.preventDefault();
    var form = $(this).parents('form');
    let action = form.attr("action");
    let type = form.attr("method");
    let result = false;
    if (flag) {
      form.find('input, textarea').each(function () {
        result = check(this);
        return result;
      });
    } else {
      result = true
    }
    let content = form.serialize()
    if (result && apply) {
      apply = false;
      $.ajax({
        url: action + "&t=" + Math.random(),
        type: type || 'POST',
        dataType: 'json',
        data: content,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
          'X-XXS-Protection': '1;mode=block',
          'X-Frame-Options': 'deny'
        },
        success: function (data: any) {
          if (data.status == 1) {
            toast(data.info)
            setTimeout(function () {
              window.location.href = data.url
            }, 1500)
          } else {
            toast(data.info)
            apply = true
            return false
          }

        },
        error: function error() {
          toast("提交失败,请稍后重试")
          apply = true;
          return false
        }
      })
    }
  })
  $("#year").text(new Date().getFullYear())
  // 获取验证码
  var countdown = 60;
  let timer2 = 0;
  $("button.getcode").on("click", function (e) {
    e = e || window.event;
    e.preventDefault();
    var $this = $(this);
    var text = $(this).text();
    var mobile = $(this).closest("form").find("input[name='mobile']").val();
    if (countdown == 60) {
      if (!$.trim(mobile).length) {
        toast("请输入手机号")
        return false;
      }
      if (!/^[1][0-9]{10}$/.test(mobile)) {
        toast('手机号格式不正确')
        return false;
      }
      var content = {
        mobile: $.trim(mobile)
      };
      $.ajax({
        url: "/index/cepin/login.html?do=sendmobilecode&t=" + Math.random(),
        type: 'POST',
        dataType: 'json',
        data: content,
        success: function (data) {
          if (data != 1) {
            toast("验证码发送失败")
          } else {
            toast("验证码发送成功，请查看手机")
          }
          $this.text(countdown + ' s').attr('disabled', "true");
          countdown--;
          timer2 = window.setInterval(function () {
            if (countdown > 0) {
              $this.text(countdown + ' s');
              countdown--;
            } else {
              $this.text(text).removeAttr('disabled');
              clearInterval(timer2);
              countdown = 60;
            }
          }, 1000);
        },
        error: function () {
          toast("验证码发送失败");
        }
      });
      return false;
    }
  });
  var dataReg = {
		m: /^[1][0-9]{10}$/
	};
  function check(element) {
    var value = $(element).val();
    var datatype = $(element).attr('datatype');
    if ($(element).attr("type") == "radio" && $(element).attr("name")) {
      value = $("input[name='" + $(element).attr("name") + "']:checked").val();
      if (!value) {
        if ($(element).attr("nullmsg")) {
          toast($(element).attr("nullmsg"))
        }
        $('html, body').animate({
          scrollTop: Math.ceil($(element).closest("li").offset().top - $('form').offset().top + $('.message').outerHeight())
        }, 300);
        return false;
      }
    } else if (!value && $(element).attr('nullmsg')) {
      toast($(element).attr('nullmsg'))
      return false;
    } else if (datatype && !dataReg[datatype].test(value)) {
      toast($(element).attr('errormsg'))
      return false;
    }
    return true;
  }
})